package com.yb.web.global;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yb.base.web.BaseAction;
import com.yb.bussiness.global.SysUserService;
import com.yb.bussiness.global.SysUserServiceImpl;
import com.yb.bussiness.global.SystemLogService;
import com.yb.bussiness.global.SystemLogServiceImpl;
import com.yb.bussiness.goods.CategoryService;
import com.yb.bussiness.goods.CategoryServiceImpl;
import com.yb.bussiness.goods.MarketBrandService;
import com.yb.bussiness.goods.MarketBrandServiceImpl;
import com.yb.bussiness.goods.TBrandTypeService;
import com.yb.bussiness.goods.TBrandTypeServiceImpl;
import com.yb.bussiness.member.MemberService;
import com.yb.bussiness.member.MemberServiceImpl;
import com.yb.bussiness.shoper.BrandService;
import com.yb.bussiness.shoper.BrandServiceImpl;
import com.yb.bussiness.shoper.TpBugRecordService;
import com.yb.bussiness.shoper.TpBuyRecordServiceImpl;
import com.yb.bussiness.statement.StatementService;
import com.yb.bussiness.statement.StatementServiceImpl;
import com.yb.bussiness.tribune.TribuneMasterService;
import com.yb.bussiness.tribune.TribuneMasterServiceImpl;
import com.yb.domain.goods.TBrandType;
import com.yb.domain.goods.TMarketBrand;
import com.yb.domain.goods.TgBrand;
import com.yb.domain.member.TsMember;
import com.yb.domain.member.TsSysuser;
import com.yb.domain.tribune.TribuneMaster;
import com.yb.util.comm.BASE64Util;
import com.yb.util.comm.CharacterUtil;
import com.yb.util.comm.Contants;
import com.yb.util.comm.RequestUtil;
import com.yb.util.framework.PageUtil;

public class SysuserAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2221699813751703241L;
	private SysUserService service;
	private BrandService brandService;
	private TsSysuser user;
	private TgBrand tgBrand;
	private TsMember member;
	private CategoryService categoryService;
	private String errorMes;
	private List rows;
	private String typeStr;
	private String markStr;
	private TBrandTypeService typeService;
	private MarketBrandService marketBrandService;
	private Long bigCategoryId;
	private Long categoryId;
	private Long[] typeId;
	private Long[] marketId;
	private TpBugRecordService recordService;
	private MemberService memberService;
	private TribuneMasterService masterService;
	private SystemLogService systemLogService;
	private int total;
	private StatementService statementservice;
	private String agreement; 
	
	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public SysuserAction() {
		service = new SysUserServiceImpl();
		brandService = new BrandServiceImpl();
		categoryService = new CategoryServiceImpl();
		typeService = new TBrandTypeServiceImpl();
		marketBrandService = new MarketBrandServiceImpl();
		recordService = new TpBuyRecordServiceImpl();
		memberService = new MemberServiceImpl();
		masterService = new TribuneMasterServiceImpl();
		systemLogService = new SystemLogServiceImpl();
        statementservice = new StatementServiceImpl();
	}

	/**
	 * 用户登录
	 * 
	 * @return
	 */
	public String login() {
		try {
			int brandId = 0;
			user.setUsername(CharacterUtil.encode(user.getUsername()));
			user = service.checkLogin(user.getUsername(), BASE64Util
					.getBASE64(user.getPassword()));
			if (null == user) {
				errorMes = "2";
			} else {
				errorMes = "1";
				if ("2".equals(user.getType())) {
					TgBrand brand = brandService.findByUserId(user.getId()
							.toString());
					if (brand != null) {
						errorMes = "5";
						brandId = brand.getId().intValue();
						RequestUtil.setLoginUser2Session(request, "brandInfo",
								brand);
					}
					TribuneMaster obj = masterService
							.queryObjByUserId(user.getId());
					if (null != obj) {
						if("1".equals(obj.getAuding())){
							user.setIsBz(1);
						}
					}
				} else if ("3".equals(user.getType())) {
					//检测是否是斑竹，1是 2否
					user.setIsBz(2);
					TribuneMaster obj = masterService
							.queryObjByUserId(user.getId());
					if (null != obj) {
						if("1".equals(obj.getAuding())){
							user.setIsBz(1);
						}
					}
					errorMes = "6";
				}
				RequestUtil.setLoginUser2Session(request,
						Contants.SESSION_USER, user);
			}
			response.getWriter().print(
					"{result:" + errorMes + ",brandId:" + brandId + "}");
		} catch (Exception e) {
			log.error("用户登录异常", e);
			try {
				response.getWriter().print("3");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 忘记密码
	 * @return
	 */
	public String resetPassword() {
		errorMes = "2";
		try {
			String userName = RequestUtil.getParam(request, "userName", "");
			String realName = RequestUtil.getParam(request, "realName", "");
			String userType = RequestUtil.getParam(request, "userType", "");
			if ("".equals(userName)||"".equals(realName)||"".equals(userType)) {
				errorMes = "2";
			} else {
				errorMes = service.resetPassword(userName,realName,userType);
			}
			response.getWriter().print(
					"{result:" + errorMes + "}");
		} catch (Exception e) {
			log.error("用户登录异常", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String changePassword() {
		try {
			String password = BASE64Util.getBASE64(user.getPassword());
			user = (TsSysuser) RequestUtil.getLoginUserFromSession(request,
					Contants.SESSION_USER);
			service.changePassword(password, user.getUsername());
			user.setPassword(password);
			RequestUtil.reSetLoginUser2Session(request, Contants.SESSION_USER,
					user);
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("修改密码失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String changeModulePassword() {
		try {
			String password = BASE64Util.getBASE64(user.getPassword());
			user = (TsSysuser) RequestUtil.getLoginUserFromSession(request,
					Contants.SESSION_USER);
			service.changeModulePassword(password, user.getUsername());
			user.setModulePassword(password);
			RequestUtil.reSetLoginUser2Session(request, Contants.SESSION_USER,
					user);
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("修改模块操作密码失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 验证用户名是否已经注册
	 * 
	 * @return
	 */
	public String checkUserName() {

		try {
			String username = RequestUtil.getParam(request, "username", "");
			user = service.checkRegister(username);
			if (null == user) {
				errorMes = "1"; // 可以注册
			} else {
				errorMes = "2";
			}
			response.getWriter().print(errorMes);
		} catch (Exception e) {
			try {
				response.getWriter().print("3");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 修改时验证用户名是否已经注册
	 * 
	 * @return
	 */
	public String modifycheckUserName() {
		String oldusername = RequestUtil.getParam(request, "oldusername", "");

		try {
			if (null != user.getUsername() && !"".equals(user.getUsername())) {
				user
						.setUsername(URLDecoder.decode(user.getUsername(),
								"utf-8"));
			}
			user = service.checkReRegister(user.getUsername(), oldusername);
			if (null == user) {
				errorMes = "1"; // 可以注册
			} else {

				errorMes = "2";
			}
			response.getWriter().print(errorMes);
		} catch (IOException e) {
			try {
				response.getWriter().print("3");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return null;
	}

	public String exit() {
		try {
			request.getSession().invalidate();
		} catch (Exception e) {
			log.error("退出错误", e);
		}
		return "exit";
	}

	public String qiantanExit() {
		try {
			request.getSession().invalidate();
		} catch (Exception e) {
			log.error("退出错误", e);
		}
		return "home";
	}

	/**
	 * 跳转到注册页面
	 */
	public String goForWordRegister() {
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
		}
		return "register";
	}

	public String saveUser() {
		try {
			user.setPassword(BASE64Util.getBASE64(user.getPassword()));
			// 未审核状态
			user.setType("4");
			user.setCreateDate(new Date());
			Long userId = service.saveUser(user);
			user.setId(userId);
			member.setSysuserId(userId);
			memberService.saveOrUpdate(member);
			RequestUtil.setLoginUser2Session(request, Contants.SESSION_USER,
					user);
		} catch (Exception e) {
			log.error("业主注册失败", e);
		}
		return "registersuccess";
	}

	public String saveBrand() {
		try {
			user.setPassword(BASE64Util.getBASE64(user.getPassword()));
			user.setCreateDate(new Date());
			// 未审核商家
			user.setType("6");
			//自己注册的商家
			user.setSource("2");
			Long userId = service.saveUser(user);
			user.setId(userId);
			tgBrand.setSysuserId(userId);
			Long brandId = brandService.saveBrand(tgBrand);
			tgBrand.setId(brandId);
			if (null != typeId) {
				for (int i = 0; i < typeId.length; i++) {
					TBrandType tbt = new TBrandType();
					tbt.setBrandId(brandId);
					tbt.setCategoryId(categoryId);
					tbt.setTypeId(new Long(typeId[i]));
					typeService.save(tbt);
				}
			} else {
				TBrandType tbt = new TBrandType();
				tbt.setBrandId(brandId);
				tbt.setCategoryId(categoryId);
				typeService.deleteByBidAndCid(brandId, categoryId);
				typeService.save(tbt);
			}
			if (null != marketId) {
				for (int i = 0; i < marketId.length; i++) {
					TMarketBrand tmb = new TMarketBrand();
					tmb.setBrandId(brandId);
					tmb.setMarketId(marketId[i]);
					marketBrandService.delete(tmb);
					marketBrandService.save(tmb);
				}
			}
			RequestUtil.setLoginUser2Session(request, Contants.SESSION_USER,
					user);
			RequestUtil.setLoginUser2Session(request, "brandInfo", tgBrand);
		} catch (Exception e) {
			log.error("商家注册失败", e);
		}
		return "registersuccess";
	}

	/**
	 * 用户注册
	 */
	public String register() {

		try {
			user.setPassword(BASE64Util.getBASE64(user.getPassword()));
			if (null != user.getUsername() && !"".equals(user.getUsername())) {
				user
						.setUsername(URLDecoder.decode(user.getUsername(),
								"utf-8"));
			}
			user.setCreateDate(new Date());
			boolean isFlag = service.saveOrUpdate(user);
			if (isFlag) {
				TsSysuser tsSys = service.checkRegister(user.getUsername());
				if (null != tsSys) {
					tgBrand.setSysuserId(tsSys.getId());
					tgBrand.setAuding("0");
					if (null != tgBrand.getName()
							&& !"".equals(tgBrand.getName())) {
						tgBrand.setName(URLDecoder.decode(tgBrand.getName(),
								"utf-8"));
					}
					if (null != tgBrand.getShopAddress()
							&& !"".equals(tgBrand.getShopAddress())) {
						tgBrand.setShopAddress(URLDecoder.decode(tgBrand
								.getShopAddress(), "utf-8"));
					}
					if (null != tgBrand.getCompanyOPerer()
							&& !"".equals(tgBrand.getCompanyOPerer())) {
						tgBrand.setCompanyOPerer(URLDecoder.decode(tgBrand
								.getCompanyOPerer(), "utf-8"));
					}
					if (null != tgBrand.getRealName()
							&& !"".equals(tgBrand.getRealName())) {
						tgBrand.setRealName(URLDecoder.decode(tgBrand
								.getRealName(), "utf-8"));
					}
					if (null != tgBrand.getCompanyName()
							&& !"".equals(tgBrand.getCompanyName())) {
						tgBrand.setCompanyName(URLDecoder.decode(tgBrand
								.getCompanyName(), "utf-8"));
					}
					boolean isTrue = brandService.saveOrUpdate(tgBrand);
					if (isTrue) {
						if (null != typeStr) {
							TgBrand tg = brandService.searchBySysId(tsSys
									.getId().intValue());
							if (null != tg) {
								String[] typeIdArry = typeStr.split("_");
								for (int i = 0; i < typeIdArry.length; i++) {

									TBrandType tbt = new TBrandType();
									tbt.setBrandId(tg.getId());
									tbt.setCategoryId(new Long(tg
											.getCategoryId()));
									tbt.setTypeId(new Long(typeIdArry[i]));
									typeService.save(tbt);
								}
								// 添加市场信息
								String[] markStrArry = markStr.split("_");
								for (int i = 0; i < markStrArry.length; i++) {

									TMarketBrand marketbrand = new TMarketBrand();
									marketbrand.setBrandId(tg.getId());
									marketbrand.setMarketId(new Long(
											markStrArry[i]));
									marketBrandService.save(marketbrand);
								}
							}
						}

						RequestUtil.setLoginUser2Session(request,
								Contants.SESSION_USER, tsSys);
						response.getWriter().print("1");
					} else {
						response.getWriter().print("2");
					}
				}
			} else {
				response.getWriter().print("2");
			}

		} catch (Exception e) {
			log.error("注册信息错误", e);
			try {
				service.deleteUserByLoginName(user.getUsername());
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * 起跳转作用跳入首页
	 * 
	 * @return
	 */
	public String goForWord() {
		return "home";
	}

	/**
	 * 验证登入身份
	 * 
	 * @return
	 */
	public String checkSheng() {
		try {
			String id = RequestUtil.getParam(request, "id", "");
			String brandId = RequestUtil.getParam(request, "brandId", "");
			if ("".equals(id)) {
				response.getWriter().print("1");
				return null;
			}
			user = service.findByUserId(Integer.parseInt(id));
			if (null == user) {
				errorMes = "1";// 未登入
			} else {
				if ("3".equals(user.getType())) {
					int count = recordService.searchBrandCountByUserId(brandId,
							id);
					if (count == 0)
						errorMes = "2";// 没有参加拼购
					else
						errorMes = "4"; // 可以评价
				} else
					errorMes = "3"; // 不是业主身份
			}
			response.getWriter().print(errorMes);
		} catch (Exception e) {
			log.error("验证登入身份异常", e);
			try {
				response.getWriter().print("4");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String addMember(){
		String id = RequestUtil.getParam(request, "id", "0");
		user = service.findByUserId(Integer.parseInt(id));
		if (user == null) {
			user = new TsSysuser();
			user.setId(Long.valueOf(0));
			user.setType("1");
		}
		return "addMember";
	}
	
	/**
	 * 用户信息查询
	 * 
	 * @return
	 */
	public String searchUser() {
		int page = RequestUtil.getParam(request, "page", 1);
		int row = RequestUtil.getParam(request, "rows", 10);
		String userName = RequestUtil.getParam(request, "userName", "");
		String userType = RequestUtil.getParam(request, "userType", "1");

		Map<String, String> parameMap = new HashMap<String, String>();
		parameMap.put("userName", userName);
		parameMap.put("type", userType);
		PageUtil pu = service.getList(parameMap, page, row);
		total = pu.getTotalRecords();
		rows = pu.getList();
		return Contants.JSONSTRING_RESULT_NAME;
	}
	/**
	 * 检测用户名是否存在
	 * 
	 * @return
	 */
	public String checkUserNameIsExistMember() {
		String username = RequestUtil.getParam(request, "username", "");
		List<TsSysuser> list = null;
		try {
			list = service.checkUserNameIsExistMember(username);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if (null == list || list.size() == 0) {
			markStr = "1";// 该用户名不存在
		} else {
			markStr = "0";// 该用户名存在
		}
		try {
			response.getWriter().print(markStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	public String addUser(){
		if(null!=user){
			user.setId(null);
			user.setCreateDate(new Date());
			user.setPassword(BASE64Util.getBASE64(user.getPassword()));
			user.setModulePassword(user.getPassword());
			service.saveUser(user);
			systemLogService.saveSystemLog(request, "用户管理", "新增用户--"+user.getUsername());
		}
		return "memberManage";
	}
	/**
	 * 删除
	 * 
	 * @return
	 */
	public String deleteById() {
		String idString = RequestUtil.getParam(request, "idString", "");
		boolean isFlag = false;
		String[] delteid = idString.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				systemLogService.saveSystemLog(request, "用户管理", "删除用户信息--"+service.findByUserId(Integer.valueOf(delteid[i])).getUsername());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		isFlag = service.deleteUser(idString);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag){
			message = "删除成功";
		}else
			message = "删除失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}
	
	public TsSysuser getUser() {
		return user;
	}

	public void setUser(TsSysuser user) {
		this.user = user;
	}

	public String getErrorMes() {
		return errorMes;
	}

	public void setErrorMes(String errorMes) {
		this.errorMes = errorMes;
	}

	public TgBrand getTgBrand() {
		return tgBrand;
	}

	public void setTgBrand(TgBrand tgBrand) {
		this.tgBrand = tgBrand;
	}

	public BrandService getBrandService() {
		return brandService;
	}

	public void setBrandService(BrandService brandService) {
		this.brandService = brandService;
	}

	public String getTypeStr() {
		return typeStr;
	}

	public void setTypeStr(String typeStr) {
		this.typeStr = typeStr;
	}

	public String getMarkStr() {
		return markStr;
	}

	public void setMarkStr(String markStr) {
		this.markStr = markStr;
	}

	public List getRows() {
		return rows;
	}

	public void setRows(List rows) {
		this.rows = rows;
	}

	public SysUserService getService() {
		return service;
	}

	public void setService(SysUserService service) {
		this.service = service;
	}

	public Long getBigCategoryId() {
		return bigCategoryId;
	}

	public void setBigCategoryId(Long bigCategoryId) {
		this.bigCategoryId = bigCategoryId;
	}

	public Long getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(Long categoryId) {
		this.categoryId = categoryId;
	}

	public Long[] getTypeId() {
		return typeId;
	}

	public void setTypeId(Long[] typeId) {
		this.typeId = typeId;
	}

	public Long[] getMarketId() {
		return marketId;
	}

	public void setMarketId(Long[] marketId) {
		this.marketId = marketId;
	}

	public TsMember getMember() {
		return member;
	}

	public void setMember(TsMember member) {
		this.member = member;
	}

    public String getAgreement() {
        return agreement;
    }

    public void setAgreement(String agreement) {
        this.agreement = agreement;
    }

}
